package com.leyou.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.item.dto.CategoryDTO;
import com.item.dto.SkuDTO;
import com.item.dto.SpuDTO;
import com.item.dto.SpuDetailDTO;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.BrandDTO;
import com.leyou.common.vo.PageResult;
import com.leyou.entity.Sku;
import com.leyou.entity.Spu;
import com.leyou.entity.SpuDetail;
import com.leyou.mapper.SkuMapper;
import com.leyou.mapper.SpuDetailMapper;
import com.leyou.mapper.SpuMapper;
import com.leyou.service.BrandService;
import com.leyou.service.CategoryService;
import com.leyou.service.GoodsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.leyou.common.constants.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_UP_KEY;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper detailMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private AmqpTemplate amqpTemplate;
//    商品列表的显示
    @Override
    public PageResult<SpuDTO> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {

        // 1 分页
        PageHelper.startPage(page,rows);
        // 2 过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();

        // 2.1 搜索条件过滤
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+key+"%");
        }
        // 2.2 上下架过滤
        if (saleable != null){
            criteria.andEqualTo("saleable",saleable);
        }
        // 2.3 默认按时间排序
        example.setOrderByClause("update_time DESC");
        // 3 查询结果
        List<Spu> list = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        // 4 封装分页结果
        PageInfo<Spu> info = new PageInfo<>(list);
        // DTO转换
        List<SpuDTO> spuDTOList = BeanHelper.copyWithCollection(list, SpuDTO.class);

        handleCategoryAndBrandName(spuDTOList);

        return new PageResult<>(info.getTotal(),info.getPages(),spuDTOList);
    }



    private void handleCategoryAndBrandName(List<SpuDTO> list) {
        for (SpuDTO spuDTO : list) {
            // 查询分类
            String categoryName = categoryService.queryCategoryByIds(spuDTO.getCategoryIds()).stream()
                    .map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);

            // 查询品牌
            BrandDTO brandDTO = brandService.queryById(spuDTO.getBrandId());
            spuDTO.setBrandName(brandDTO.getName());

        }

    }

//    新增商品
    @Transactional
    public void save(SpuDTO spuDTO) {
        // 从dto中取出spu信息
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 保存spu
        spu.setId(null);
        spu.setCreateTime(null);
        spu.setSaleable(null);
        int count = spuMapper.insertSelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 初始化SpuDetail信息
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        spuDetail.setSpuId(spu.getId());
        // 保存spu详情
        count = detailMapper.insertSelective(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        // 准备sku数据
        List<SkuDTO> skuDTOList = spuDTO.getSkus();
        List<Sku> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOList) {
            skuDTO.setSpuId(spu.getId());
            skuList.add(BeanHelper.copyProperties(skuDTO, Sku.class));
        }
        // 保存sku
        count = skuMapper.insertList(skuList);
        if (count != skuList.size()) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    @Transactional //开启事务
    @Override
    public void updateSaleable(Long id, Boolean saleable) {
//        更新SPU
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
//根据主键更新数据,T对象里面有什么属性就更新什么属性,如果T对象没有主键,抛出异常
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 2.更新sku
//        准备要更新的数据
        Sku sku = new Sku();
        sku.setEnable(saleable);
        //准备更新的匹配条件
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId",id);
        count = skuMapper.updateByExampleSelective(sku,example);

//       查到的和更新成功的记录数进行比较
        int size = skuMapper.selectCountByExample(example);
        if (size != count){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }


        // 发送mq消息
        String key = saleable ? ITEM_UP_KEY : ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME,key, id);

    }

//    根据ID查询SpuDetail
    public SpuDetailDTO querySpuDetailById(Long id) {
        SpuDetail spuDetail = detailMapper.selectByPrimaryKey(id);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

//    根据spuID查询sku
    public List<SkuDTO> querySkuListBySpuId(Long id) {
        Sku s = new Sku();
        s.setSpuId(id);
        List<Sku> list = skuMapper.select(s);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

//    修改商品
    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        Long spuId = spuDTO.getId();
        if (spuId == null) {
            // 请求参数有误
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        // 1.删除sku
        Sku sku = new Sku();
        sku.setId(spuId);
        // 查询数量
        int size = skuMapper.selectCount(sku);
        if (size > 0){
            // 删除
            int count = skuMapper.delete(sku);
            if (count != size){
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }

        // 2.更新spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(null);
        spu.setCreateTime(null);
        spu.setUpdateTime(null);
        ////根据主键进行更新
        ////只会更新不是null的数据
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 3.更新spuDetail
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        spuDetail.setSpuId(spuId);
        spuDetail.setCreateTime(null);
        spuDetail.setUpdateTime(null);
        count = detailMapper.updateByPrimaryKeySelective(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        // 4.新增sku
        List<SkuDTO> dtoList = spuDTO.getSkus();
        List<Sku> skuList = dtoList.stream().map(dto -> {
            dto.setEnable(false);
//            // 添加spu的id
            dto.setSpuId(spuId);
            return BeanHelper.copyProperties(dto, Sku.class);
        }).collect(Collectors.toList());

        count = skuMapper.insertList(skuList);
        if (count != skuList.size()){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

    }

    //根据spu的id查询spu
    @Override
    public SpuDTO querySpuById(Long id) {


        return BeanHelper.copyProperties(this.spuMapper.selectByPrimaryKey(id),SpuDTO.class);
    }

}
